package com.oldroid.apps.getit.ui;

import java.io.File;
import java.util.ArrayList;

import com.oldroid.apps.getit.R;
import com.oldroid.apps.getit.ui.adapter.ShortcutAdapter;
import com.oldroid.apps.getit.util.Shortcut;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;

public class BookmarkFragment extends Fragment {
	private static final String TAG = "BookmarkFragment";
	private ListView shortcutListView;
	private ListView bookmarkListView;
	private TextView mTextView;
	private final FragmentManager mFragmentManager;
	public ArrayList<Shortcut> mBookmark;
	private BrowserFragment mBrowserFragment;

	public BookmarkFragment(FragmentManager fm, BrowserFragment browserFragment) {
		mBrowserFragment = browserFragment;
		mBookmark = new ArrayList<Shortcut>();
		mFragmentManager = fm;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_bookmark, null);
		shortcutListView = (ListView) rootView
				.findViewById(R.id.browser_shortcut);
		File externalLoc = Environment.getExternalStorageDirectory();
		String sdcard = externalLoc.getAbsolutePath() + File.pathSeparator;
		String downloads = sdcard + "GetIt" + File.pathSeparator;
		final Shortcut[] list = new Shortcut[] { new Shortcut(sdcard, "Home"),
				new Shortcut(downloads, "Downloads") };
		// TODO: need one more shortcut!
		shortcutListView.setAdapter(new ShortcutAdapter(getActivity(),
				R.layout.shortcut_row, list, true));
		shortcutListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long id) {
				final Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.putExtra("filepath", list[position].getPath());
				mBrowserFragment.populateFiles(list[position].getPath());
				refresh();
			}
		});
		
		bookmarkListView = (ListView) rootView
				.findViewById(R.id.browser_bookmark);
		if (mBookmark.size() > 0)
			bookmarkListView.setAdapter(new ShortcutAdapter(getActivity(),
					R.layout.shortcut_row, (Shortcut[]) mBookmark.toArray(),
					false));
		else{
			mTextView = (TextView) rootView.findViewById(R.id.browser_label_bookmark_empty);
			mTextView.setVisibility(View.VISIBLE);
		}
		
		return rootView;
	}
	
	private void refresh(){
		mFragmentManager.findFragmentByTag("browser");
		if(mFragmentManager!=null){
			Log.d(TAG, "mFragmentManager is not null");
			
		}
	}

}
